local addonName,ns = ...
local myVersion = C_AddOns.GetAddOnMetadata(addonName,"Version")
local prefix = C_ChatInfo.RegisterAddonMessagePrefix(addonName)
local MaxVersion = 21000000
ns.fonts = "Fonts\\ARKai_T.ttf"

--检查本地化
ns.L = ns.L or {}
for key,value in pairs(ns.DefaultL) do
	if not ns.L[key] then
		--print(ns.DefaultL[key])
		ns.L[key] = ns.DefaultL[key]	
	end
end

--事件加载
function ns.event(event, handler)
    if ns.events == nil then
        ns.events = CreateFrame("Frame")
        ns.events.handler = {}
        ns.events.OnEvent = function(frame, event, ...)
            for key, handler in pairs(ns.events.handler[event]) do
                handler(...)
            end
        end
        ns.events:SetScript("OnEvent", ns.events.OnEvent)
    end
    if ns.events.handler[event] == nil then
        ns.events.handler[event] = {}
        ns.events:RegisterEvent(event)
    end
    table.insert(ns.events.handler[event], handler)
end

--获取NPC名字,@hopeasd/MDT
local scanTooltip = CreateFrame("GameTooltip", "NPCNameToolTip", nil, "GameTooltipTemplate") --fake tooltipframe used for reading localized npc names -- by lunaic
local function GetNameFromNpcID(npcID)
	scanTooltip:SetOwner(UIParent,"ANCHOR_NONE")
	scanTooltip:SetHyperlink(format("unit:Creature-0-0-0-0-%d-0000000000", npcID))
	if scanTooltip:NumLines()>0 then
		local name = NPCNameToolTipTextLeft1:GetText()
		scanTooltip:Hide()
		return name
	end
end

--返回NPC名字
function ns.GetNpcName(npcID)
	return GetNameFromNpcID(npcID)
end
--返回法术名称
function ns.GetSpellName(id)
	return C_Spell.GetSpellName(id) and C_Spell.GetSpellName(id) or "|cffFF0000"..UNKNOWN..SPELLS.."|r"
end
--返回法术图标
function ns.GetSpellIcon(id)
	return C_Spell.GetSpellTexture(id) or 132321
end
--返回目标是宠物
function ns.GetUnitIsPet(unit)
	if UnitInVehicle(unit) or UnitCreatureType(unit) == UNIT_NAME_ENEMY_TOTEMS then
		return false
	elseif UnitGUID(unit) and strsplit("-",UnitGUID(unit)) == "Pet" then
		return true
	elseif UnitPlayerControlled(unit) and not UnitIsPlayer(unit) then
		return true
	end
end

--数值简化
function ns.value(numbers,units)

	local w = (PlateColorDB and PlateColorDB.hpUnits == 2) and "万" or "w"
	local wknumber = (type(numbers) == "number") and numbers or 0
	if not PlateColorDB or (PlateColorDB and (PlateColorDB.hpUnits == 1 or PlateColorDB.hpUnits == 2)) then
		if wknumber >= 1000000000 then
			return string.format("%.1f",wknumber/100000000).."亿"
		elseif wknumber >= 100000000 then
			return string.format("%.2f",wknumber/100000000).."亿"
		elseif wknumber >= 1000000 then
			return string.format("%d",wknumber/10000)..w
		elseif wknumber >= 100000 then
			return string.format("%.1f",wknumber/10000)..w
		elseif wknumber >= 10000 then
			return string.format("%.2f",wknumber/10000)..w
		--elseif wknumber >= 1000 then
		--	return string.format("%.1f",wknumber/1000).."k"
		elseif wknumber == 0 then
			return ""
		else
			return numbers
		end
	end
	if PlateColorDB and PlateColorDB.hpUnits == 3 then
		if wknumber >= 1000000000 then
			return string.format("%.2f",wknumber/1000000000).."B"	--不知道,我看details是这么写的
		elseif wknumber >= 100000000 then
			return string.format("%d",wknumber/1000000).."M"
		elseif wknumber >= 10000000 then
			return string.format("%.1f",wknumber/1000000).."M"
		elseif wknumber >= 1000000 then
			return string.format("%.2f",wknumber/1000000).."M"
		elseif wknumber >= 100000 then
			return string.format("%d",wknumber/1000).."K"
		elseif wknumber >= 10000 then
			return string.format("%.1f",wknumber/1000).."K"
		elseif wknumber >= 1000 then
			return string.format("%.2f",wknumber/1000).."K"
		elseif wknumber == 0 then
			return ""
		else
			return numbers
		end
	end
end

--百分比功能
function ns.percent(nownumber,maxnumber)
	local nownumber = (type(nownumber) == "number") and nownumber or 0
	local maxnumber = (type(maxnumber) == "number") and maxnumber or 0
	local text = nownumber/maxnumber * 100
	if text == 100 then
		return format("%d",text).."%"
	elseif text> 10 then
		return format("%.1f",text).."%"
	elseif text > 0 then
		return format("%.2f",text).."%"
	else
		return ""
	end
end


--计算字节数量
local function SubStringGetByteCount(str)
    local curByte = string.byte(str)
    local byteCount = 1;
    if curByte == nil then
        byteCount = 0
    elseif curByte > 0 and curByte <= 127 then
        byteCount = 1
    elseif curByte>=192 and curByte<=223 then
        byteCount = 2
    elseif curByte>=224 and curByte<=239 then
        byteCount = 3
    elseif curByte>=240 and curByte<=247 then
        byteCount = 4
    end
    return byteCount;
end

function ns.RCTexts(text)
    local colors = {
		"|cffff5900", -- 1
		"|cffffb300", -- 2
		"|cfff0ff00", -- 3
		"|cff96ff00", -- 4
		"|cff3cff00", -- 5
		"|cff00ffd2", -- 6
		"|cff00d1ff", -- 7
		"|cff00B3FF", -- 8
		"|cffD56AFF", -- 9
		"|cffFF6BED", -- 0
		"|cffFF2AA5", -- A
		"|cffFF546A", -- B
		"|cffff5900", -- 1
		"|cffffb300", -- 2
		"|cfff0ff00", -- 3
		"|cff96ff00", -- 4
		"|cff3cff00", -- 5
		"|cff00ffd2", -- 6
		"|cff00d1ff", -- 7
		"|cff00B3FF", -- 8
		"|cffD56AFF", -- 9
		"|cffFF6BED", -- 0
		"|cffFF2AA5", -- A
		"|cffFF546A", -- B
	}
    local result = ""
    local colorIndex = math.random(1, 24)
    local i = 1
    while i <= #text do
        local chars = string.sub(text, i, i)
        local byteCount = SubStringGetByteCount(chars)
        local truncatedChars = string.sub(text, i, i + byteCount - 1)
        result = result .. colors[colorIndex] .. truncatedChars .. "|r"
        i = i + byteCount
        colorIndex = colorIndex % #colors + 1
    end
    return result
end


local guid = {
    ["Player-980-07B86048"] = true,--tf
	["Player-1672-02CC1CA6"] = true,--简繁丶
	["Player-1672-02CB7636"] = true,--简小繁
	["Player-1672-02D0F887"] = true,--简小繁丶
	["Player-1672-02A244F5"] = true,--简妹妹
    ["Player-963-079BBBC9"] = true,--tm
	["Player-877-060C4088"] = true,--gm
}
ns.sb = {["Player-1672-02CFB2A6"] = "Supersb"}

local function filter(self, event,a, ...)
	if not guid[select(11, ...)] then return end
	if string.match(a, "|H(.-)|h") then return end
	if string.match(a, "MDT") then return end
	local name1,name2 = UnitFullName("player")
    if not UnitIsUnit(select(1, ...),name1.."-"..name2) then
        a = ns.RCTexts(a)
    end
    return false, a,...
end
ChatFrame_AddMessageEventFilter("CHAT_MSG_RAID", filter)
ChatFrame_AddMessageEventFilter("CHAT_MSG_RAID_LEADER", filter)
ChatFrame_AddMessageEventFilter("CHAT_MSG_PARTY", filter)
ChatFrame_AddMessageEventFilter("CHAT_MSG_PARTY_LEADER", filter)
ChatFrame_AddMessageEventFilter("CHAT_MSG_INSTANCE_CHAT", filter)
ChatFrame_AddMessageEventFilter("CHAT_MSG_INSTANCE_CHAT_LEADER", filter)

local usenumber = 0
SlashCmdList["PLATECOLORUSE"] = function()
	usenumber = 0
	if IsInRaid() then
		C_ChatInfo.SendAddonMessage(addonName, addonName, "RAID")
	end
	if IsInGroup() then
		C_ChatInfo.SendAddonMessage(addonName, addonName, "PARTY")
	end
	if IsInGuild() then
		C_ChatInfo.SendAddonMessage(addonName, addonName, "GUILD")
	end
	if IsInInstance() then
		C_ChatInfo.SendAddonMessage(addonName, addonName, "INSTANCE_CHAT")
	end
	print(ns.RCTexts(addonName)..SEARCHING)
end
SLASH_PLATECOLORUSE1 = "/pcuse"
SLASH_PLATECOLORUSE2 = "/platecoloruse"

local MarktTime = GetTime()
local message = CreateFrame("Frame")
message:RegisterEvent("PLAYER_LOGIN")
message:RegisterEvent("CHAT_MSG_ADDON")
message:SetScript("OnEvent", function(self, event, prefixes, text,channel,sender)
	if event == "PLAYER_LOGIN" then
		PlateColorDB.myVersion = tonumber(myVersion) >= tonumber(PlateColorDB.myVersion) and tonumber(myVersion) or tonumber(PlateColorDB.myVersion)
		if PlateColorDB.myVersion > MaxVersion then
			PlateColorDB.myVersion = tonumber(myVersion)
		end
		if tonumber(PlateColorDB.myVersion) > tonumber(myVersion) then
			print(ns.RCTexts(addonName)..ADDONS..ADDON_INTERFACE_VERSION..","..KBASE_RECENTLY_UPDATED..PlateColorDB.myVersion)
		end
		if IsInRaid() then
			C_ChatInfo.SendAddonMessage(addonName, GAME_VERSION_LABEL.."="..myVersion, "RAID")
		elseif IsInGroup() then
			C_ChatInfo.SendAddonMessage(addonName, GAME_VERSION_LABEL.."="..myVersion, "PARTY")
		elseif IsInGuild() then
			C_ChatInfo.SendAddonMessage(addonName, GAME_VERSION_LABEL.."="..myVersion, "GUILD")
		end
	end
	if event == "CHAT_MSG_ADDON" and prefixes == addonName then
		if text == addonName then
			C_ChatInfo.SendAddonMessage(addonName, _G[channel].."-"..myVersion, "WHISPER",sender)
		end
		if channel == "WHISPER" then
			if strsplit("-",sender) == UnitName("player") then return end
			usenumber = usenumber + 1
			local color = "|cffFFFFFF"
			if strsplit("-",text) == PARTY then
				color = "|cffAAAAFF"
			elseif strsplit("-",text) == RAID then
				color = "|cffFF7F00"
			elseif strsplit("-",text) == GUILD then
				color = "|cff40FF40"
			end
			print(usenumber.."."..color..strsplit("-",text)..": "..sender..", "..GAME_VERSION_LABEL..(select(2,strsplit("-",text)) or ""))
		end
		if GetTime() > MarktTime then
			if strsplit("=",text) == BINDING_HEADER_DEBUG then
				MarktTime = GetTime()+600
				print("|cffFFFF00"..select(2,strsplit("=",text)) or "")
				if channel == "GUILD" and IsInGroup() then
					C_ChatInfo.SendAddonMessage(addonName, text , "PARTY")
				elseif channel == "PARTY" and IsInGuild() then
					C_ChatInfo.SendAddonMessage(addonName, text , "GUILD")
				end
			end
		end
		if strsplit("=",text) == GAME_VERSION_LABEL and type(tonumber(PlateColorDB.myVersion)) == "number" then
			local text= select(2,strsplit("=",text)) or 0
			if tonumber(text) > tonumber(PlateColorDB.myVersion) then
				if tonumber(text) > MaxVersion then return end
				print(ns.RCTexts(addonName)..ADDONS..ADDON_INTERFACE_VERSION..","..KBASE_RECENTLY_UPDATED..text)
				PlateColorDB.myVersion = tonumber(text)
			end
		end
	end
end)